package com.caldremch.androidfoundation.http;


import android.app.Application;
import android.content.Context;

import com.caldremch.androidfoundation.http.request.PostRequest;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 *
 * @author Caldremch
 * @date 2018/11/6
 * @Email caldremch@163.com
 * @describe http管理类
 *
 **/
public final class XHttp {

    public static final int DEFAULT_MILLISECONDS = 60000;             //默认的超时时间

    private static Context sContext;
    private  OkHttpClient.Builder mOkHttpClientBuilder;                 //okhttp请求的客户端
    private  Retrofit.Builder mRetrofitBuilder;
    private static volatile XHttp singleton = null;

    private XHttp() {

        mOkHttpClientBuilder = new OkHttpClient.Builder();
        mOkHttpClientBuilder.connectTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        mOkHttpClientBuilder.readTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        mOkHttpClientBuilder.writeTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        mRetrofitBuilder = new Retrofit.Builder();
        mRetrofitBuilder.baseUrl(ServerConstant.TEST_URl);
        mRetrofitBuilder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());

    }

    public static XHttp getInstance() {
        checkInitialize();
        if (singleton == null) {
            synchronized (XHttp.class) {
                if (singleton == null) {
                    singleton = new XHttp();
                }
            }
        }
        return singleton;
    }

    //get the context, for cache or others
    public static void init(Application app) {
        sContext = app;
    }

    private static void checkInitialize() {
        if (sContext == null) {
            throw new ExceptionInInitializerError("Please invoke XHttp.init() in Application");
        }
    }


    public static OkHttpClient getOkHttpClient() {
        return getInstance().mOkHttpClientBuilder.build();
    }

    /**
     * 用于自定义OkHttpClientBuilder
     */
    public static OkHttpClient.Builder getOkHttpClientBuilder() {
        return getInstance().mOkHttpClientBuilder;
    }

    /**
     * 用于自定义Retrofit
     */
    public static Retrofit.Builder getRetrofitBuilder() {
        return getInstance().mRetrofitBuilder;
    }

    /**
     * POST请求
     *
     * @param suffixUrl
     * @return
     */
    public static PostRequest post(String suffixUrl) {
        return new PostRequest(suffixUrl);
    }
}
